#!/usr/bin/env python3
# app_simple.py - 简化版Flask后端API服务（用于测试）
from flask import Flask, request, jsonify
from flask_cors import CORS
import os
import uuid

from werkzeug.security import generate_password_hash
from werkzeug.utils import secure_filename
from datetime import datetime

# 导入数据库集成模块
from database_integration import db_manager, init_database, test_database_connection

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-change-in-production'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB max file size

CORS(app, resources={r"/api/*": {"origins": "*"}})

# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs('temp', exist_ok=True)

# 全局变量存储面试会话（内存中的会话状态）
interview_sessions = {}

class InterviewSession:
    def __init__(self, session_id, job_position, resume_path, user_id=None):
        self.session_id = session_id
        self.job_position = job_position
        self.resume_path = resume_path
        self.user_id = user_id
        self.resume_text = "这是一个测试简历内容"  # 简化版本
        self.current_round = 0
        self.max_rounds = 3
        self.is_identity_verified = False
        self.db_session_id = None  # 数据库中的会话ID

# 工具函数
def hash_password(password):
    """密码哈希"""
    import hashlib
    return hashlib.sha256(password.encode()).hexdigest()

def create_default_user():
    try:
        existing_user = db_manager.get_user_by_email("test@example.com")
        if not existing_user:
            user_id = db_manager.create_user(
                username="测试用户",
                email="test@example.com",
                password_hash=generate_password_hash("password"),
                role="candidate",
            )
            print(f"✅ 创建默认用户成功，ID: {user_id}")
        else:
            print("ℹ️ 默认用户已存在")
    except Exception as e:
        print("❌ 创建默认用户失败:", e)


# API路由
@app.route('/api/register', methods=['POST'])
def register():
    """用户注册"""
    try:
        data = request.get_json()
        username = data.get('username')
        email = data.get('email')
        password = data.get('password')
        
        if not all([username, email, password]):
            return jsonify({'error': '请填写所有必填字段'}), 400
        
        # 检查用户是否已存在
        existing_user = db_manager.get_user_by_email(email)
        if existing_user:
            return jsonify({'error': '该邮箱已被注册'}), 400
        
        # 创建新用户
        user_id = db_manager.create_user(
            username=username,
            email=email,
            password_hash=hash_password(password)
        )
        
        return jsonify({
            'message': '注册成功',
            'user_id': user_id
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        email = data.get('email')
        password = data.get('password')
        
        if not all([email, password]):
            return jsonify({'error': '请填写邮箱和密码'}), 400
        
        # 验证用户
        user = db_manager.get_user_by_email(email)
        if not user or user.password_hash != hash_password(password):
            return jsonify({'error': '邮箱或密码错误'}), 401
        
        return jsonify({
            'message': '登录成功',
            'user': {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'role': user.role
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/upload-resume', methods=['POST'])
def upload_resume():
    """上传简历文件"""
    try:
        if 'resume' not in request.files:
            return jsonify({'error': '没有上传文件'}), 400

        file = request.files['resume']
        job_position = request.form.get('job_position', '软件工程师')
        user_id = request.form.get('user_id')  # 从前端获取用户ID

        if file.filename == '':
            return jsonify({'error': '文件名为空'}), 400

        if file:
            # 生成唯一的会话ID
            session_id = str(uuid.uuid4())
            filename = secure_filename(file.filename)
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{session_id}_{filename}")
            file.save(file_path)

            # 创建面试会话（内存）
            session = InterviewSession(session_id, job_position, file_path, user_id)
            interview_sessions[session_id] = session

            # 如果有用户ID，创建数据库会话记录
            if user_id:
                try:
                    db_session_id = db_manager.create_interview_session(
                        user_id=int(user_id),
                        session_type='ai_interview'
                    )
                    session.db_session_id = db_session_id
                except Exception as e:
                    print(f"创建数据库会话记录失败: {e}")

            return jsonify({
                'session_id': session_id,
                'resume_text': session.resume_text[:200] + '...' if len(session.resume_text) > 200 else session.resume_text,
                'job_position': job_position
            })

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/verify-identity/<session_id>', methods=['POST'])
def verify_identity_api(session_id):
    """身份验证接口"""
    try:
        if session_id not in interview_sessions:
            return jsonify({'error': '会话不存在'}), 404

        return jsonify({'message': '请对准摄像头进行人脸验证'})

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/capture-face/<session_id>', methods=['POST'])
def capture_face_api(session_id):
    """拍摄当前人脸"""
    try:
        if session_id not in interview_sessions:
            return jsonify({'error': '会话不存在'}), 404

        # 简化版本，直接返回验证成功
        session = interview_sessions[session_id]
        session.is_identity_verified = True

        return jsonify({
            'verified': True,
            'similarity_score': 0.85,  # 模拟相似度分数
            'message': '身份验证成功'
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/start-interview/<session_id>', methods=['POST'])
def start_interview_api(session_id):
    """开始面试"""
    try:
        if session_id not in interview_sessions:
            return jsonify({'error': '会话不存在'}), 404

        session = interview_sessions[session_id]

        if not session.is_identity_verified:
            return jsonify({'error': '请先完成身份验证'}), 400

        # 生成开场问题（简化版本）
        first_question = f"您好，欢迎参加{session.job_position}岗位的面试。请先简单介绍一下自己吧。"
        session.current_round = 1

        # 保存对话到数据库
        if session.db_session_id:
            try:
                db_manager.save_dialogue(
                    session_id=session.db_session_id,
                    round_num=session.current_round,
                    speaker='system',
                    content=first_question
                )
            except Exception as e:
                print(f"保存对话失败: {e}")

        return jsonify({
            'question': first_question,
            'round': session.current_round,
            'total_rounds': session.max_rounds
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/health')
def health_check():
    """健康检查接口"""
    db_status = test_database_connection()
    return jsonify({
        'status': 'healthy',
        'message': 'AI面试系统运行正常',
        'database': 'connected' if db_status else 'disconnected'
    })

@app.route('/api/user-stats/<int:user_id>')
def get_user_stats(user_id):
    """获取用户统计信息"""
    try:
        interview_count = db_manager.get_user_interview_count(user_id)
        average_score = db_manager.get_user_average_score(user_id)
        
        return jsonify({
            'user_id': user_id,
            'interview_count': interview_count,
            'average_score': average_score
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 应用启动时初始化数据库
def initialize_app():
    """应用启动时的初始化"""
    print("🔧 初始化应用...")
    
    # 测试数据库连接
    if test_database_connection():
        print("✅ 数据库连接正常")
        
        # 初始化数据库表
        if init_database():
            print("✅ 数据库表初始化完成")
            
            # 创建默认用户
            create_default_user()
        else:
            print("❌ 数据库表初始化失败")
    else:
        print("❌ 数据库连接失败")

if __name__ == '__main__':
    print("🚀 AI面试系统后端启动中...")
    print("📡 API服务地址: http://localhost:5000")
    print("💾 数据库集成: 已启用")
    
    # 初始化应用
    initialize_app()
    
    app.run(debug=True, host='0.0.0.0', port=5000)

